<?php

namespace App\Http\Controllers\Api\Common;

use App\Http\Controllers\Controller;
use App\Http\Requests\Common\UploadRequest;
use App\Trip\Tencent\Cloud\SDK\COS\Cos;
use App\Trip\UploadService;
use Exception;

class UploadController extends Controller
{
    public UploadService $service;
    public string|int    $user_id;

    public function __construct()
    {
        $this->service = new UploadService();
        $this->user_id = auth()->id() ?: '';
    }

    /**
     * @throws Exception
     */
    public function upload(UploadRequest $request)
    {
        //获取上传的文件
        $files = $request->file('file');
        if (!$files) {
            throw new Exception('没有文件');
        }

        $scene       = $request->input('business');
        $uid         = md5($this->user_id);
        $business    = $this->user_id ? $scene."/{$uid}" : $scene;
        $return      = [];
        $return_urls = [];
        if (is_array($files)) {
            foreach ($files as $key => $file) {
                $return[] = $this->service->upload($file, $business);
            }
        } else {
            $file     = $files;
            $return[] = $this->service->upload($file, $business);
        }
        $cos = new Cos();
        /**
         * @var UploadService $ret
         */
        foreach ($return as $ret) {
            $return_urls[] = $cos->uploadRemoteImage($ret->getFileContent(), $ret->getFileName());
        }

        return $this->success('上传成功', [
            'url' => $return_urls,
        ]);

    }


}
